package com.x.share.mid.http.client;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This example demonstrates how to create secure connections with a custom SSL
 * context.
 */
public class SSLHttpClient {
	Logger logger = LoggerFactory.getLogger(SSLHttpClient.class);

	SSLConnectionSocketFactory sslsf;

	public SSLHttpClient(String p12Cert, String password) throws Exception {
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		FileInputStream instream = new FileInputStream(new File(p12Cert));
		try {
			keyStore.load(instream, password.toCharArray());
		} finally {
			instream.close();
		}
		// Trust own CA and all self-signed certs
		SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build();
		// Allow TLSv1 protocol only
		sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
				SSLConnectionSocketFactory.getDefaultHostnameVerifier());
	}

	public String get(String url) throws Exception {
		logger.info(">>>> ssl get: {}", url);
		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
		try {
			HttpGet httpget = new HttpGet(url);
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				HttpEntity entity = response.getEntity();
				logger.info(">>>> respone status: {}", response.getStatusLine());
				if (entity != null) {
					String rlt = EntityUtils.toString(entity, "UTF-8");
					logger.info(">>>> content: {}", rlt);
					return rlt;
				}
			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
		return null;
	}

	public String post(String url, String params) throws Exception {
		logger.info(">>>> ssl post url: {}", url);
		logger.info(">>>> ssl post params: {}", params);
		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
		try {
			HttpPost httppost = new HttpPost(url);
			httppost.setEntity(new StringEntity(params, "UTF-8"));
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				logger.info(">>>> respone status: {}", response.getStatusLine());
				if (entity != null) {
					String rlt = EntityUtils.toString(entity, "UTF-8");
					logger.info(">>>> content: {}", rlt);
					return rlt;
				}
			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
		return null;
	}

//	public final static void main(String[] args) throws Exception {
//		SSLHttpClient client = new SSLHttpClient("/Users/chenheng/Work/weixin/xiao_mai_hui/apiclient_cert.p12",
//				"1230701702");
//		String rlt = client.get("https://api.mch.weixin.qq.com/secapi/pay/refund");
//		System.out.println(rlt);
//	}
}